package com.hsj.springai.service;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

public class QRCodeGenerator {

    public static void main(String[] args) {
        String backgroundImagePath = "/Users/jackbryant/IdeaProjects/springai-study/springai/src/main/resources/background.png"; // 背景图路径
        String qrCodeUrl = "https://www.example.com"; // 二维码内容
        String outputImagePath = "/Users/jackbryant/IdeaProjects/springai-study/springai/src/main/resources/output.png"; // 输出图片路径

        try {
            // 生成二维码
            BufferedImage qrCodeImage = generateQRCodeImage(qrCodeUrl, 100, 100);

            // 加载背景图
            BufferedImage backgroundImage = ImageIO.read(new File(backgroundImagePath));

            // 合并图片
            BufferedImage combinedImage = combineImages(backgroundImage, qrCodeImage, 50, 250);

            // 保存合并后的图片
            ImageIO.write(combinedImage, "png", new File(outputImagePath));

            System.out.println("图片已成功生成并保存到: " + outputImagePath);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
    }

    private static BufferedImage generateQRCodeImage(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    private static BufferedImage combineImages(BufferedImage background, BufferedImage qrCode, int x, int y) {
        // 创建一个新的BufferedImage，类型为RGB
        BufferedImage combined = new BufferedImage(background.getWidth(), background.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = combined.createGraphics();

        // 绘制背景图
        g.drawImage(background, 0, 0, null);

        // 绘制二维码图
        g.drawImage(qrCode, x, y, null);

        g.dispose();
        return combined;
    }
}